package com.wilmer.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.wilmer.common.core.redis.RedisCache;
import com.wilmer.bean.PhoneInfoResponseBean;
import com.wilmer.bean.TokenBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class GetWxPhoneUtil {

    private static final Logger log = LoggerFactory.getLogger(GetWxPhoneUtil.class);

    @Resource
    private AccessTokenUtil accessTokenUtil;
    @Resource
    private RedisCache redisCache;

    @Value("${wechat.app_phone_url}")
    private String app_phone_url;

    public String ensureAccessToken() {
        Object cachedToken = redisCache.getCacheObject("access_token");
        if (Objects.isNull(cachedToken) || redisCache.getExpire("access_token") <= 600000L) {
            return refreshAccessToken();
        } else {
            log.info("access_token is valid");
            return (String) cachedToken;
        }
    }

    private String refreshAccessToken() {
        TokenBean tokenBean = accessTokenUtil.getToken();
        redisCache.setCacheObject("access_token", tokenBean.getAccess_token(), 7200, TimeUnit.SECONDS);
        log.info("Refreshed access_token successfully");
        return tokenBean.getAccess_token();
    }

    public String getPhone(String code) {

        HashMap<String, Object> phoneMap = new HashMap<>();
        phoneMap.put("code",code);

        String s = JSONUtil.toJsonStr(phoneMap);
        String res = HttpUtil.post(app_phone_url+"?access_token="+ensureAccessToken(),s);

        System.out.println(res);
        PhoneInfoResponseBean phoneInfoResponseBean = JSONUtil.toBean(res, PhoneInfoResponseBean.class);

        return phoneInfoResponseBean.getPhone_info().getPhoneNumber();
    }
}
